package logic

import (
	"context"
	"encoding/json"
	"home-sys/cache"
	"home-sys/moder"
	"time"

	"home-sys/homerpc/homerpc"
	"home-sys/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserListLogic) UserList(in *homerpc.UserListRequest) (*homerpc.UserListResponse, error) {
	// todo: add your logic here and delete this line
	var user []moder.User
	result, _ := cache.Rdb.Get(l.ctx, "userList").Result()
	if result == "" {
		moder.DB.Scopes(moder.Paginate(int(in.Page), int(in.Size))).Find(&user)
		marshal, _ := json.Marshal(user)
		cache.Rdb.Set(l.ctx, "userList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	var userList []*homerpc.UserList
	for _, users := range user {
		list := homerpc.UserList{
			Username: users.Username,
			Password: users.Password,
			UserId:   int64(users.ID),
		}
		userList = append(userList, &list)

	}

	return &homerpc.UserListResponse{
		List: userList,
	}, nil
}
